package com.accp.vehiclecare.action.syhaction;

import com.accp.vehiclecare.biz.syhbiz.EmpBiz;
import com.accp.vehiclecare.vo.syhvo.Employee;
import com.accp.vehiclecare.vo.syhvo.Syfunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("api/emp")
public class EmpAction {

    @Autowired
    private EmpBiz biz;
    /**
     * 登录
     * @param zh
     * @param mm
     * @param session
     * @return
     */
    @GetMapping("login")
    public Map<String,Object> queryOne(String zh, String mm, HttpSession session) throws Exception{
        Map<String,Object>  map = new HashMap<>();
        Employee emp = biz.queryOne(zh, mm);
        if (emp != null) {
            session.setAttribute("USER", emp);
            map.put("code", 200);
            map.put("msg", "ok");
            map.put("emp", emp);
        } else {
            map.put("code", 301);
            map.put("msg", "login_error");
        }
        return map;
    }

    /**
     * 注销
     * @param session
     * @return
     */
    @GetMapping("loginOut")
    public Map<String,Object> loginOut(HttpSession session) throws Exception{
        System.out.println("已注销");
        Map<String,Object> map = new HashMap<>();
        session.invalidate();
        map.put("code", 200);
        map.put("msg", "ok");

        return map;
    }

    @PostMapping("getFunTree")
    public List getUserFunTree(@RequestBody Employee emp, HttpSession session) throws Exception{
        List tree = new ArrayList();
        Set<String> menuNames = new TreeSet<String>();// 剔除重复值，保存一级菜单名称
        for (Syfunction fun : emp.getRole().getSyfunctions()) {
            menuNames.add(fun.getSyfunction().getSyfunctionname());
        }
        // 遍历一级菜单名称，生成二级菜单项
        for (String name : menuNames) {
            // 节点【初始化】
            Map<String, Object> node = new HashMap<String, Object>();
            node.put("id", 0);// 0:根级菜单
            node.put("text", name);
            List nodeChild = new ArrayList();
            for (Syfunction fun : emp.getRole().getSyfunctions()) {
                // 匹配是否是当前菜单的子项
                if (name.equals(fun.getSyfunction().getSyfunctionname())) {
                    Map<String, Object> n = new HashMap<String, Object>();
                    n.put("id", fun.getSyfunctioncode());
                    n.put("text", fun.getSyfunctionname());
                    nodeChild.add(n);
                }
            }
            node.put("children", nodeChild);
            tree.add(node);
        }
        return tree;
    }
}
